package com.gomtel.smartdevice.ui.activity.tools;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.api.BleManager;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.bean.UserContent;
import com.gomtel.smartdevice.bt.ble.BLEDevice;
import com.gomtel.smartdevice.interfaces.OnScannerListener;
import com.gomtel.smartdevice.moudle.db.entity.AppConfigurationInfo;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.moudle.event.EventCode;
import com.gomtel.smartdevice.moudle.rxtools.EventBusUtil;
import com.gomtel.smartdevice.ui.dialog.ProgressDialog;
import com.gomtel.smartdevice.ui.dialog.ShowDialog;
import com.gomtel.smartdevice.utils.CommonUtils;
import com.xihespace.xihecommonlibrary.activity.CaptureActivity;

import butterknife.BindView;

import static com.xihespace.xihecommonlibrary.activity.CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN;
import static com.xihespace.xihecommonlibrary.activity.CaptureActivity.RESULT_CODE_QR_SCAN;

/**
 * Created by Administrator on 2018/5/28 0028.
 * 设备链接
 */

public class DeviceConnectionActivity extends WatchAppBaseActivity implements View.OnClickListener {

    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.img_btn_black)
    ImageButton img_btn_black;
    @BindView(R.id.sn_scan)
    View sn_scan;
    @BindView(R.id.hint_sn_code)
    EditText hint_sn_code;
    @BindView(R.id.bind)
    TextView bind;
    @BindView(R.id.smssdk_search)
    TextView smssdk_search;
    private boolean isNoDevices = true;
    private Runnable runnable;

    @Override
    protected void registerEvent(CommonEvent commonevent) {
        switch (commonevent.getCode()) {
            case EventCode.FINISH_SELECT:
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                finish();
                break;
            case EventCode.LINK_FAILED:
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                break;

        }
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_device_connection;
    }

    @Override
    protected void initClass() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        title_name.setText(getString(R.string.app_name));
    }

    @Override
    protected void initListener() {
        img_btn_black.setOnClickListener(this);
        bind.setOnClickListener(this);
        smssdk_search.setOnClickListener(this);
        sn_scan.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_btn_black:
                finish();
                break;
            case R.id.bind:
                isNoDevices = true;
                serachForLanya(hint_sn_code.getText().toString(), 1);
                break;
            case R.id.smssdk_search:
                startActivity(new Intent(DeviceConnectionActivity.this, SearchActivity.class));
                break;
            case R.id.sn_scan:
                isNoDevices = true;
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, 500);
                break;
        }
    }

    /**
     * 二维码回调结果
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 500 && resultCode == RESULT_CODE_QR_SCAN && data != null) {
            String result = data.getExtras().getString(INTENT_EXTRA_KEY_QR_SCAN);
            Log.e(TAG, "onActivityResult:" + result);
            serachForLanya(result, 0);
        }
    }

    private ProgressDialog progressDialog;
    private boolean isFirst = true;

    private void serachForLanya(String text, int type) {
        if (!TextUtils.isEmpty(text) && text.length() == 9 && CommonUtils.isNumber(text)) {
            com.clj.fastble.BleManager instance = com.clj.fastble.BleManager.getInstance();
            if (!instance.isBlueEnable()) {
                instance.enableBluetooth();
            }
            progressDialog = ShowDialog.newInstance().showProgressStatus(this, "搜索中...");
            progressDialog.show();
            BleManager.getInstance().scan(10000/*超时设置*/, new OnScannerListener() {
                @Override
                public void onComplete() {
                    isFirst = true;
                    isNoDevices = false;
                }

                @Override
                public void onError(Throwable throwable) {
                    isFirst = true;
                    CommonUtils.showToast(DeviceConnectionActivity.this, "异常错误，请重新连接");
                }

                @Override
                public void onNext(BLEDevice bleDevice) {
                    // 同一设备会被搜索到多次,请做好过滤
                    if (isFirst && bleDevice != null && bleDevice.getServiceSn() != null && text.equals(String.valueOf(Integer.valueOf(bleDevice.getServiceSn(), 16)))) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        progressDialog = ShowDialog.newInstance().showProgressStatus(DeviceConnectionActivity.this, "连接中...");
                        progressDialog.show();
                        isFirst = false;
                        Log.e(TAG, bleDevice.getMacAddress() + "bleDevice.getMacAddress()");
                        AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
                        if (appConfigurationInfo != null) {
                            dataManager.UpDataAppConfigurationInfo(new AppConfigurationInfo(appConfigurationInfo.getId(), UserContent.UserName, bleDevice.getMacAddress(), bleDevice.getName(),
                                    appConfigurationInfo.getObjectiveToRemind(), appConfigurationInfo.getCallReminder(), appConfigurationInfo.getSedentaryRemind()));
                        } else {
                            dataManager.insertAppConfigurationInfo(new AppConfigurationInfo(UserContent.UserName, bleDevice.getMacAddress(), bleDevice.getName(), 0, 0, 0));
                        }
                        EventBusUtil.sendEvent(new CommonEvent(EventCode.LOCAL_AREA_LINKS));

//                        BleManager.getInstance().connect(bleDevice.getMacAddress(), new OnConnectListener() {
//
//                            @Override
//                            public void onSuccess() {
//                                BleManager.getInstance().stopScan();
//                                isFirst = true;
//                                toastUtil.showToast("已连接上,请点击手表右边的按键进行匹配");
//                                progressDialog.dismiss();
//                                if (runnable != null) {
//                                    CommonUtils.getHandler().removeCallbacks(runnable);
//                                }
//                                AppConfigurationInfo appConfigurationInfo = dataManager.queryAppConfigurationInfo(UserContent.UserName);
//                                if (appConfigurationInfo != null) {
//                                    dataManager.UpDataAppConfigurationInfo(new AppConfigurationInfo(appConfigurationInfo.getId(), UserContent.UserName, bleDevice.getMacAddress(), bleDevice.getName(),
//                                            appConfigurationInfo.getObjectiveToRemind(), appConfigurationInfo.getCallReminder(), appConfigurationInfo.getSedentaryRemind()));
//                                } else {
//                                    dataManager.insertAppConfigurationInfo(new AppConfigurationInfo(UserContent.UserName, bleDevice.getMacAddress(), bleDevice.getName(), 0, 0, 0));
//                                }
//                                DataClass.onlineStatus = true;
//                                WatchApplication.getInstance().getMainActivity().getHandler().sendEmptyMessage(EventCode.CTIONCONTENTSTATUS);
//                                EventBusUtil.sendEvent(new CommonEvent(EventCode.CTIONCONTENTSTATUS, "已连接"));
//                                EventBusUtil.sendEvent(new CommonEvent(EventCode.PERSONAGE_UP_DATA));
//                            }
//
//                            @Override
//                            public void onFailure(Throwable e) {
//                                e.printStackTrace();
//                                toastUtil.showToast("连接失败");
//                                progressDialog.dismiss();
//                                if (runnable != null) {
//                                    CommonUtils.getHandler().removeCallbacks(runnable);
//                                }
//                            }
//
//                            @Override
//                            public void onTimeout() {
//                                toastUtil.showToast("连接超时");
//                                progressDialog.dismiss();
//                                if (runnable != null) {
//                                    CommonUtils.getHandler().removeCallbacks(runnable);
//                                }
//                            }
//                        });
                    }
                }
            });
            runnable = () -> {
                if (isNoDevices) {
                    CommonUtils.showToast(this, "没有获取到对应的设备");
                }
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                BleManager.getInstance().stopScan();
                runnable = null;
            };
            CommonUtils.getHandler().postDelayed(runnable, 10000);
        } else if (type == 0) {
            CommonUtils.showToast(this, "请扫描正确二维码或者条形码");
        } else if (type == 1) {
            CommonUtils.showToast(this, "请输入正确SN码");
        } else {
            CommonUtils.showToast(this, "格式错误");
        }
    }

    @Override
    protected void onDestroy() {
        BleManager.getInstance().stopScan();
        if (runnable != null) {
            CommonUtils.getHandler().removeCallbacks(runnable);
        }
        super.onDestroy();
    }
}
